package cn.itcast.service.cargo.impl;

import cn.itcast.dao.cargo.FactoryDao;
import cn.itcast.domain.cargo.Factory;
import cn.itcast.domain.cargo.FactoryExample;
import cn.itcast.service.cargo.FactoryService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class FactoryServiceImpl implements FactoryService {

    @Autowired
    private FactoryDao factoryDao;

    //厂家的分页
    @Override
    public PageInfo<Factory> findByPage(FactoryExample factoryExample, int pageNum, int pageSize) {
        //1.设置当前页与页面大小
        PageHelper.startPage(pageNum,pageSize);
        //2 .查询数据
        List<Factory> factoryList = factoryDao.selectByExample(factoryExample);

        //3. 构建PageInfo
        PageInfo<Factory> pageInfo = new PageInfo<>(factoryList);
        return pageInfo;
    }

    //根据条件查询
    @Override
    public List<Factory> findAll(FactoryExample factoryExample) {
        List<Factory> factoryList = factoryDao.selectByExample(factoryExample);
        return factoryList;
    }

    //根据主键查询厂家
    @Override
    public Factory findById(String id) {
        return factoryDao.selectByPrimaryKey(id);
    }

    //保存厂家
    @Override
    public void save(Factory factory) {
        //补全id
        factory.setId(UUID.randomUUID().toString());
        //补全创建时间与更新时间，因为这两个字段不能为空
        factory.setCreateTime(new Date());
        factory.setUpdateTime(new Date());
        factoryDao.insertSelective(factory);
    }

    //更新厂家
    @Override
    public void update(Factory factory) {
        factory.setUpdateTime(new Date());
        factoryDao.updateByPrimaryKeySelective(factory);
    }

    //根据主键删除厂家
    @Override
    public void delete(String id) {
        factoryDao.deleteByPrimaryKey(id);
    }

    //根据厂家的名字查找厂家
    @Override
    public Factory findByName(String factoryName) {
        FactoryExample factoryExample = new FactoryExample();
        //创建条件
        factoryExample.createCriteria().andFactoryNameEqualTo(factoryName);
        List<Factory> factoryList = factoryDao.selectByExample(factoryExample);
        return factoryList.get(0);
    }
}
